package com.ossjk.ossjkservlet.system.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;

import com.ossjk.core.base.servlet.BaseServlet;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.vo.AjaxReturn;
import com.ossjk.core.vo.Page;
import com.ossjk.ossjkservlet.common.Constant;
import com.ossjk.ossjkservlet.system.dao.GoodsDao;
import com.ossjk.ossjkservlet.system.dao.GoodstypeDao;
import com.ossjk.ossjkservlet.system.pojo.Goods;
import com.ossjk.ossjkservlet.system.pojo.Goodstype;
import com.ossjk.ossjkservlet.util.UUIDUtils;

@MultipartConfig // 使用MultipartConfig注解标注改servlet能够接受文件上传的请求
@WebServlet("/system/goods.do")
public class GoodsServlet extends BaseServlet {

	private Logger logger = Logger.getLogger(GoodsServlet.class);

	private GoodsDao GoodsDao = new GoodsDao();
	private GoodstypeDao goodstypeDao = new GoodstypeDao();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
		try {
			req.setCharacterEncoding("UTF-8");
			resp.setCharacterEncoding("UTF-8");
			String method = getMethod(req);
			if ("list".equals(method)) {
				list(req, resp);
			} else if ("toInsert".equals(method)) {
				toInsert(req, resp);
			} else if ("insert".equals(method)) {
				insert(req, resp);
			} else if ("toUpdate".equals(method)) {
				toUpdate(req, resp);
			} else if ("update".equals(method)) {
				update(req, resp);
			} else if ("delete".equals(method)) {
				delete(req, resp);
			} else if ("batchDelete".equals(method)) {
				batchDelete(req, resp);
			}
		} catch (Exception e) {
			logger.error("", e);
			// 重定向
			redirect(req, resp, req.getContextPath() + "/system/index.do?method=toError");
		}
	}

	/**
	 * 列表
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// select * from Goods
		// 通过getParamtoObject获取page对象，page 已经有了pageNum ，pageSize
		Page page = getParamtoObject(Page.class, req);
		String name = req.getParameter("name");

//		String sql = "select * from Goods";
		String sql = "select g.*,gst.name as gstname from goods g LEFT JOIN goodstype gst on g.gtid = gst.id";
		List list2 = new ArrayList();
		if (!CommonUtil.isBlank(name)) {
			sql += " where  g.name like  CONCAT('%',?,'%') ";
			list2.add(name);
			page.getPrams().put("name", name);
		}
		System.out.println(sql);
		// selectByPageCount 返回值类型是page page 里面带有了一些查询的数据的
		// selectByPage 返回值类型是list 只有查询结果集的内容
		page = GoodsDao.selectByPageCount(sql, page, list2.toArray());
		req.setAttribute("page", page);
		forward(req, resp, "/WEB-INF/page/system/goods/list.jsp");
	}

	/**
	 * 去增加
	 * 
	 * @param req
	 * @param resp
	 */
	public void toInsert(HttpServletRequest req, HttpServletResponse resp) {
		try {
			// 查询商品类型表
			List<Goodstype> goodstypes = goodstypeDao.selectAll();
			req.setAttribute("goodstypes", goodstypes);
			forward(req, resp, "/WEB-INF/page/system/goods/edit.jsp");
		} catch (Exception e) {
			logger.error("", e);
			redirect(req, resp, req.getContextPath() + "/system/index.do?method=toError");
		}
	}

	/**
	 * 去更新
	 * 
	 * @param req
	 * @param resp
	 */
	public void toUpdate(HttpServletRequest req, HttpServletResponse resp) {
		try {
			// 查询商品类型表
			List<Goodstype> goodstypes = goodstypeDao.selectAll();
			req.setAttribute("goodstypes", goodstypes);
			req.setAttribute("record", GoodsDao.selectById(req.getParameter("id")));
			forward(req, resp, "/WEB-INF/page/system/goods/edit.jsp");
		} catch (Exception e) {
			logger.error("", e);
			redirect(req, resp, req.getContextPath() + "/system/index.do?method=toError");
		}
	}

	/**
	 * 增加
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void insert(HttpServletRequest req, HttpServletResponse resp) {
		try {

			Part part = req.getPart("pic");
			String picPath = null;
			if (!CommonUtil.isBlank(part) && part.getSize() > 0) {
				Collection<Part> list = req.getParts();
				String disposition = part.getHeader("Content-Disposition");
				String suffix = disposition.substring(disposition.lastIndexOf("."), disposition.length() - 1);
				// 随机的生存一个32的字符串
				String filename = UUID.randomUUID() + suffix;
				// 获取上传的文件名
				InputStream is = part.getInputStream();
				// 动态获取服务器的路径
				String serverpath = req.getServletContext().getRealPath("upload");
				File dir = new File(serverpath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				String filePath = serverpath + "/" + filename;
				File file = new File(filePath);
				if (!file.exists()) {
					file.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(file);
				byte[] bty = new byte[1024];
				int length = 0;
				while ((length = is.read(bty)) != -1) {
					fos.write(bty, 0, length);
				}
				fos.close();
				is.close();
				// 图片路径
				picPath = "/upload/" + filename;
			}

			// 保存Goods对象到数据库
			Goods Goods = getParamtoObject(Goods.class, req);
			Goods.setPic(picPath);
			// 把日期格式的数据设置到对象中
			// String birthStr = req.getParameter("birth");
			// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// Goods.setBirth(sdf.parse(birthStr));

			// id没有、字符串类型的id、uuid
			Goods.setId(UUIDUtils.generateUUID());
			if (GoodsDao.insert(Goods) > 0) {
				renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_SUCCESS, Constant.RETURN_MESSAGE_SUCCESS));
			} else {
				renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_ERROR, Constant.RETURN_MESSAGE_ERROR));
			}

		} catch (Exception e) {
			logger.error("", e);
			renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_EXCEPTION, Constant.RETURN_MESSAGE_EXCEPTION));
		}
	}

	/**
	 * 更新
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void update(HttpServletRequest req, HttpServletResponse resp) {
		try {
			// getParamtoObject他没有帮我们封装date类型的数据
			Goods Goods = getParamtoObject(Goods.class, req);
			// String birthStr = req.getParameter("birth");
			// Goods.setBirth(CommonUtil.isoFormat.parse(birthStr));
			// 选择性修改,对象如果有空值，就不修改
			if (GoodsDao.updateBySelected(Goods) > 0) {
				renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_SUCCESS, Constant.RETURN_MESSAGE_SUCCESS));
			} else {
				renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_ERROR, Constant.RETURN_MESSAGE_ERROR));
			}
		} catch (Exception e) {
			logger.error("", e);
			renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_EXCEPTION, Constant.RETURN_MESSAGE_EXCEPTION));
		}
	}

	/**
	 * 删除
	 * 
	 * @param req
	 * @param resp
	 */
	public void delete(HttpServletRequest req, HttpServletResponse resp) {
		try {
			if (GoodsDao.delete(req.getParameter("id")) > 0) {
				renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_SUCCESS, Constant.RETURN_MESSAGE_SUCCESS));
			} else {
				renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_ERROR, Constant.RETURN_MESSAGE_ERROR));
			}
		} catch (Exception e) {
			logger.error("", e);
			renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_EXCEPTION, Constant.RETURN_MESSAGE_EXCEPTION));
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param req
	 * @param resp
	 */
	public void batchDelete(HttpServletRequest req, HttpServletResponse resp) {
		try {
			if (GoodsDao.batchDelete(req.getParameterValues("ids")) > 0) {
				renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_SUCCESS, Constant.RETURN_MESSAGE_SUCCESS));
			} else {
				renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_ERROR, Constant.RETURN_MESSAGE_ERROR));
			}
		} catch (Exception e) {
			logger.error("", e);
			renderAjaxReturn(resp, new AjaxReturn(Constant.RETURN_CODE_EXCEPTION, Constant.RETURN_MESSAGE_EXCEPTION));
		}
	}

}
